package com.tuni.birthdaymoney.web.controller;

import java.security.Principal;
import java.util.Calendar;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tuni.birthdaymoney.persistence.entity.NotificationSettings;
import com.tuni.birthdaymoney.persistence.entity.Person;
import com.tuni.birthdaymoney.service.PersonService;
import com.tuni.birthdaymoney.service.SettingsService;
import com.tuni.birthdaymoney.service.UserService;
import com.tuni.birthdaymoney.web.model.HomePage;
import com.tuni.birthdaymoney.web.model.MasterPage;

@Controller
public class HomeController {

    @Autowired
    private PersonService personService;

    @Autowired
    private UserService userService;

    @Autowired
    private SettingsService settingsService;

    // private static Iterable<Integer> createAgesList(Iterable<Person> persons)
    // {
    // List<Integer> result = new ArrayList<Integer>();
    // Calendar now = Calendar.getInstance();
    // for (Person p : persons) {
    // result.add(p.getNextAge(now));
    // }
    // return result;
    // }

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home(Principal principal, Map<String, Object> homePageMap) {
        MasterPage masterPageModel = new MasterPage(userService.getUserByEmail(principal.getName()), false);
        homePageMap.put("masterPageModel", masterPageModel);

        NotificationSettings settings = settingsService.loadNotificationSettings();
        Integer period = settings.getNotificationPeriod();

        HomePage homePageModel = new HomePage();
        Iterable<Person> peopleToday = personService.getPeopleWithBirthdayAt(Calendar.getInstance());
        Iterable<Person> peopleSoon = personService.getPeopleWithBirthdaySoon(Calendar.getInstance(), period);
        // Iterable<Integer> peopleTodayAges = createAgesList(peopleToday);
        // Iterable<Integer> peopleSoonAges = createAgesList(peopleSoon);

        homePageModel.setPeopleToday(peopleToday);
        homePageModel.setPeopleSoon(peopleSoon);
        // homePageModel.setPeopleTodayAge(peopleTodayAges);
        // homePageModel.setPeopleSoonAge(peopleSoonAges);
        homePageMap.put("homePageModel", homePageModel);
        return "home";
    }
}
